﻿#ifndef KERNEL_LIST_H
#define KERNEL_LIST_H

// 指针域结构体
struct list_head {
    struct list_head *next, *prev;
};

// 相当于struct list_head name = {.next=&name, .prev=&name}
#define LIST_HEAD_INIT(name) { &(name), &(name) }

// 为name赋值struct list_name属性
#define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name)

// 初始化指针域结构体
static inline void INIT_LIST_HEAD(struct list_head *list) {
    list->next = list;
    list->prev = list;
}

// 节点插在prev和next之间
static inline void __list_add(struct list_head *new,
                              struct list_head *prev,
                              struct list_head *next) {
    next->prev = new;
    new->next = next;
    new->prev = prev;
    prev->next = new;
}

// 头插
static inline void list_add(struct list_head *head, struct list_head *new) {
    __list_add(new, head, head->next);
}

// 尾插
static inline void list_add_tail(struct list_head *head, struct list_head *new) {
    __list_add(new, head->prev, head);
}

// 置空前后指针
static inline void __list_del(struct list_head *prev, struct list_head *next) {
    next->prev = prev;
    prev->next = next;
}

// 将指定节点 entry 从链表结构中剔除（并没有free）
// 并将其前后指针置空
static inline void list_del(struct list_head *entry) {
    __list_del(entry->prev, entry->next);
    entry->next = (void *) 0;
    entry->prev = (void *) 0;
}

// 将指定节点 entry 从链表结构中剔除
// 并将其前后指针指向自身
static inline void list_del_init(struct list_head *entry) {
    __list_del(entry->prev, entry->next);
    INIT_LIST_HEAD(entry);
}

/**
* list_entry ? get the struct for this entry
* @ptr:    the &struct list_head pointer.    移动的小结构体对应的地址
* @type:    the type of the struct this is embedded in.  大结构体类型 （struct kernel_list）
* @member:    the name of the list_struct within the struct. 小结构体在大结构体里面的成员名list
*///返回值为大结构体地址
#define list_entry(ptr, type, member) \
    ((type *)((char *)(ptr)-(size_t)(&((type *)0)->member)))


//向后遍历
#define list_for_each(pos, head) \
    for (pos = (head)->next; pos != (head); \
            pos = pos->next)


/**
* list_for_each_prev    -    iterate over a list backwards
* @pos:    the &struct list_head to use as a loop counter.
* @head:    the head for your list.
*/
//向前遍历
#define list_for_each_prev(pos, head) \
    for (pos = (head)->prev; pos != (head); \
            pos = pos->prev)


//遍历时，保留pos后缀节点
#define list_for_each_safe(pos, n, head) \
    for (pos = (head)->next, n = pos->next; pos != (head); \
            pos = n, n = pos->next)

/**
* list_for_each_entry    -    iterate over list of given type
* @pos:    the type * to use as a loop counter. 大结构体指针
* @head:    the head for your list.    小结构体指针
* @member:    the name of the list_struct within the struct. 小结构体在大结构体里面的成员名list
*/
//向后直接遍历得到大结构体
#define list_for_each_entry(pos, head, member)                \
    for (pos = list_entry((head)->next, typeof(*pos), member);    \
            &pos->member != (head);                     \
            pos = list_entry(pos->member.next, typeof(*pos), member))

#endif // KERNEL_LIST_H
